/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.core;

import java.util.logging.Logger;

import com.gadglet.params.ReqErrorTypes;
import com.gadglet.servlets.SignedRequestServlet;

/**
 * RequestHandler loader. 
 * 
 * First try to load according to gadget definition
 * 2nd try according to web.xml definition
 * 3rd try with system default
 *
 */
public class RequestHandlerFactory {
	static Logger log = Logger.getLogger(SignedRequestServlet.class.getName());
	protected final static String gadgetRequestHandelerClassName = "RequestHandler";
	protected final static String gadgetsPackageRoot = "com.gadglet.gadgets";

	public static BasicRequestHandler getGadgetRequestHandler(
			String gadgetName, String gadgetsRootPackageName, String gadgetHandlerPackageName, String contentName)
			throws RequestException {
		
		String subRequestHandlerName = "";
		if(contentName!=null)
			subRequestHandlerName = contentName+".";

		String handlerClassName = null;
		BasicRequestHandler handler = null;

		if (gadgetHandlerPackageName != null && !gadgetHandlerPackageName.isEmpty()) {
			handlerClassName = gadgetHandlerPackageName+ "."+subRequestHandlerName+ gadgetRequestHandelerClassName;;
		} else {
			if (gadgetsRootPackageName == null)
				gadgetsRootPackageName = gadgetsPackageRoot;
			handlerClassName = gadgetsRootPackageName + "." + gadgetName
					+ ".server."+subRequestHandlerName+ gadgetRequestHandelerClassName;
		}

		try {
			Class<?> c = Class.forName(handlerClassName);
			handler = (BasicRequestHandler) c.newInstance();
		} catch (Exception e) {
			if(gadgetHandlerPackageName!=null)
				
				log.severe("gadgetName=" + gadgetName+", gadgetHandlerClassName= "+gadgetHandlerPackageName+" doesn't seems to be a handler. Check your Gadget definition");
			
			else
			log.severe("gadgetName=" + gadgetName + ", handlerClassName="
					+ handlerClassName + " doesn't seems to be a handler. Check your web.xml param 'GadgetsRootPackageName' ");
			
			throw new RequestException(ReqErrorTypes.UNRECOGNIZED_GADGET);
		}

		return handler;

	}

}
